package com.example.shiyun.UI;

import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;

import com.example.shiyun.Adapter.Index_RecyclerAdaper;
import com.example.shiyun.MainActivity;
import com.example.shiyun.Pojo.Pojo_SentenceData;
import com.example.shiyun.Pojo.Pojo_citydata;
import com.example.shiyun.Pojo.Pojo_index_listview;
import com.example.shiyun.R;
import com.example.shiyun.Util.Util;
import com.example.shiyun.Util.Util_Okhttp;
import com.fivehundredpx.android.blur.BlurringView;
import com.lwj.widget.loadingdialog.LoadingDialog;
import com.lwj.widget.loadingdialog.SimpleLoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 程序主界面，与功能
 */
public class Index extends AppCompatActivity {
    //组件
    /*主页面*/
    private ImageView index_bj;
    private ImageView index_more;
    private TextView index_city;
    private TextView index_temperature;
    private TextView index_weather;
    private TextView index_quality;
    private TextView index_humidity;
    private RecyclerView index_recyclerview;
    private ScrollView index_scroll;
    private SwipeRefreshLayout index_refresh;
    private DrawerLayout index_drawer;
    /*滑动菜单*/
    private BlurringView blurring_view;
    private ImageView sideslip_card_bj;
    private EditText sideslip_ed_search;
    private TextView sideslip_search;
    private TextView sideslip_text;
    private ListView sideslip_listview;
    private ImageView sideslip_img;
    private FrameLayout layout;
    private TextView text;
    //全局
    private LinearLayoutManager linearLayoutManager;
    private String data_json,search;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_index);
        //设置沉浸模式
        Util.Setimmersion(getWindow());
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide();
        //EventBus注册
        EventBus.getDefault().register(this);
        //初始化数据库
        LitePal.initialize(this);
        LitePal.getDatabase();
        //初始化
        initView();
        inifuction();
    }
    //初始化组件
    private void initView() {
        //主界面
        index_bj = (ImageView) findViewById(R.id.index_bj);
        index_more = (ImageView) findViewById(R.id.index_more);
        index_city = (TextView) findViewById(R.id.index_city);
        index_temperature = (TextView) findViewById(R.id.index_temperature);
        index_weather = (TextView) findViewById(R.id.index_weather);
        index_quality = (TextView) findViewById(R.id.index_quality);
        index_humidity = (TextView) findViewById(R.id.index_humidity);
        index_recyclerview = (RecyclerView) findViewById(R.id.index_recyclerview);
        index_scroll = (ScrollView) findViewById(R.id.index_scroll);
        index_refresh = (SwipeRefreshLayout) findViewById(R.id.index_refresh);
        index_drawer=findViewById(R.id.index_drawer);
        //滑动菜单
        layout=findViewById(R.id.layout);
        sideslip_card_bj = (ImageView) findViewById(R.id.sideslip_card_bj);
        sideslip_ed_search = (EditText) findViewById(R.id.sideslip_ed_search);
        sideslip_search = (TextView) findViewById(R.id.sideslip_search);
        sideslip_text = (TextView) findViewById(R.id.sideslip_text);
        sideslip_listview = (ListView) findViewById(R.id.sideslip_listview);
        text=findViewById(R.id.text);
        sideslip_img = findViewById(R.id.sideslip_img);
        blurring_view = (BlurringView) findViewById(R.id.blurring_view);
        //设置背景为毛玻璃
        blurring_view.setBlurredView(sideslip_img);
        //是为了确保scrollView——mNoHorizontalScrollView他的子孙不能获得焦点
        index_scroll.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        //解决滑动冲突
        linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        //设置layout不可穿透点击
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

    }
    //初始化功能
    private void inifuction() {
        /*主页面功能*/
        //设置壁纸
        wallpaper();
        //设置手动下拉刷新
        index_refresh.setColorSchemeResources(R.color.lan, R.color.lv, R.color.cheng);
        index_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Refresh_data();
            }
        });
        //设置点开菜单
        index_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                index_drawer.openDrawer(Gravity.LEFT);
            }
        });
//        //添加数据
//        list = new ArrayList<>();
//        for (int i = 0; i < 15; i++) {
//            list.add(new Pojo_index_listview("星期一", "07/10", "多云", "28~30°C", R.mipmap.cloudy));
//        }
//        index_recyclerview.setLayoutManager(linearLayoutManager);
//        //创建适配器
//        Index_RecyclerAdaper adapter = new Index_RecyclerAdaper(list, this);
//        //设置适配器
//        index_recyclerview.setAdapter(adapter);

        /*侧滑菜单功能*/
        //设置侧滑菜单项
        inilist();
        //设置gif图
        Glide.with(this).load(R.mipmap.sideslip_city_bg).into(sideslip_card_bj);
        //设置侧滑菜单中的搜索
        search();
        //自动下拉更新
        index_refresh.post(new Runnable() {
            @Override
            public void run() {
                Refresh_data();
            }
        });
    }
    //设置侧滑菜单的listview
    private void inilist()
    {
        final List<String> list = new ArrayList<>();
        list.add("分享天气");
        list.add("反馈");
        list.add("设置");
        list.add("退出程序");
        list.add("更多功能尽情期待！");
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
        sideslip_listview.setAdapter(adapter);
        sideslip_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position)
                {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        new AlertDialog.Builder(Index.this)
                                .setTitle("提示！")
                                .setMessage("是否退出程序？")
                                .setCancelable(false)
                                .setNegativeButton("取消",null)
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        Util.exitApp(Index.this);
                                    }
                                }).show();

                        break;
                }
            }
        });
    }
    //设置侧滑菜单中的搜索
    private void search()
    {
        sideslip_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //检查搜索是否为空
                search = sideslip_ed_search.getText().toString().trim();
                if (TextUtils.isEmpty(search)) {
                    Util.showmeg("请输入您要查找的城市",Index.this);
                    return;
                }
                //获取静态资源中的json数据,将json数据变成字符串
                StringBuilder stringBuilder = new StringBuilder();
                try {
                    //获取assets资源管理器
                    AssetManager assetManager = Index.this.getAssets();
                    //通过管理器打开文件并读取
                    BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open("city.json")));
                    String line;
                    while ((line = bf.readLine()) != null) {
                        stringBuilder.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //得到完整的数据
                data_json=stringBuilder.toString();
                //检查网络
                if (Util.isNetworkConnected(Index.this))
                {
                    //开启线程2,判断是否有改城市
                    new Thread(()->{
                        try {
                            String xx = null;
                            JSONObject jsonObject = new JSONObject(data_json);
                            if(jsonObject.has(search))
                            {
                                xx=jsonObject.getString(search);
                                //开启异步线程更新ui
                                String finalXx = xx;
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        new AlertDialog.Builder(Index.this)
                                                .setTitle("添加信息？")
                                                .setMessage("您确定要添加"+search+"城市信息吗？")
                                                .setCancelable(false)
                                                .setNegativeButton("取消",null)
                                                .setPositiveButton("添加", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialogInterface, int i) {
                                                        sideslip_ed_search.setText("");
                                                        //找到城市编码finalXx
                                                        Util_Okhttp.ok_get(finalXx);
                                                        //添加等待框
                                                        SimpleLoadingDialog simpleLoadingDialog=new SimpleLoadingDialog(Index.this);
                                                        simpleLoadingDialog.showFirst("添加中......");
                                                        simpleLoadingDialog.showResult("加载中......");
                                                        simpleLoadingDialog.dismissDelay(2000, new LoadingDialog.DismissDelayEndCallback() {
                                                            @Override
                                                            public void onEnd(LoadingDialog dialog) {
                                                                //主界面刷新
                                                                index_refresh.post(new Runnable() {
                                                                    @Override
                                                                    public void run() {
                                                                        index_refresh.setRefreshing(true);
                                                                        List<Pojo_citydata> citydata = LitePal.findAll(Pojo_citydata.class);
                                                                        update_ui(citydata);
                                                                        index_refresh.setRefreshing(false);
                                                                    }
                                                                });
                                                                //提示成功添加
                                                                Util.showmeg( search+"添加成功！",Index.this);
                                                                index_drawer.closeDrawer(Gravity.LEFT);
                                                            }
                                                        });
                                                    }
                                                }).show();
                                    }
                                });
                            }else
                            {
                                Util.showmeg( "找不到该城市信息！",Index.this);
                            }
                        } catch (JSONException e) {
                            Util.showmeg( "暂无城市信息！",Index.this);
                        }
                    }).start();
                }else
                {
                    Util.showmeg( "添加失败，请检查网络！",Index.this);
                }

            }
        });
    }
    //接收EventBus传来的数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receive_data(String data)
    {
        Util.litepal_data(data);
    }
    //设置下拉刷新数据
    public void Refresh_data()
    {
        if (Util.isNetworkConnected(Index.this))
        {
            try {
                //查询citykey
                List<Pojo_citydata> citydata = LitePal.findAll(Pojo_citydata.class);
                String citykey = citydata.get(0).getCitykey();
                //解析
                Util_Okhttp.ok_get(citykey);
                //更新ui
                update_ui(citydata );

                //侧滑每日一句更新
                Util_Okhttp.ok_get_Sentence();
                List<Pojo_SentenceData> SentenceData = LitePal.findAll(Pojo_SentenceData.class);
                sideslip_text.setText(SentenceData.get(0).getNote());

                Util.showmeg("刷新成功",Index.this);
            }catch (Exception e)
            {
                Util.showmeg("当前无数据，请添加城市！",Index.this);
                //设置下拉刷新为假
                index_refresh.setRefreshing(false);
            }
        }else
        {
            //更新ui
            //查询citykey
            List<Pojo_citydata> citydata = LitePal.findAll(Pojo_citydata.class);
            update_ui(citydata);
            //侧滑每日一句更新
            List<Pojo_SentenceData> SentenceData = LitePal.findAll(Pojo_SentenceData.class);
            sideslip_text.setText(SentenceData.get(0).getNote());
            Util.showmeg("网络飞走了！",Index.this);
            //设置下拉刷新为假
            index_refresh.setRefreshing(false);
        }
    }
    //更新ui
    public void update_ui(List<Pojo_citydata> citydata )
    {
        //更新ui
        index_city.setText(citydata.get(0).getCity());
        index_temperature.setText(citydata.get(0).getWendu());
        index_weather.setText(citydata.get(0).getType());
        index_quality.setText("天气质量:"+citydata.get(0).getQuality());
        index_humidity.setText("相对湿度:"+citydata.get(0).getShidu());

        //添加数据
        List<Pojo_index_listview> list = new ArrayList<>();
        for (int i =0; i <15; i++) {
            Log.d("xx",citydata.size()+"");
            String[] date = citydata.get(i).getYmd().split("-");
            String low = citydata.get(i).getLow().substring(3);
            String high = citydata.get(i).getHigh().substring(3);
            list.add(new Pojo_index_listview(citydata.get(i).getWeek(),date[1]+"/"+date[2],citydata.get(i).getType() , low+"~"+high, Util.weather_chart(citydata.get(i).getType())));
        }
        index_recyclerview.setLayoutManager(linearLayoutManager);
        //创建适配器
        Index_RecyclerAdaper adapter = new Index_RecyclerAdaper(list, Index.this);
        //设置适配器
        index_recyclerview.setAdapter(adapter);
        //设置下拉刷新为假
        index_refresh.setRefreshing(false);
    }
    //更换壁纸
    public void wallpaper()
    {
        //获取本地时间
        SimpleDateFormat format = new SimpleDateFormat("HH");
        Date date = new Date();
        Integer time = Integer.valueOf(format.format(date));
        if (time>=6&&time<18)
        {
            index_bj.setImageResource(R.mipmap.index_bg_day);
            sideslip_img.setImageResource(R.mipmap.index_bg_day);
        }else if (time>=18)
        {
            index_bj.setImageResource(R.mipmap.index_bg_night);
            sideslip_img.setImageResource(R.mipmap.index_bg_night);
            sideslip_text.setTextColor(Color.WHITE);
            text.setTextColor(Color.WHITE);
        }else if (time>=00&&time<6)
        {
            index_bj.setImageResource(R.mipmap.index_bg_night_dark);
            sideslip_img.setImageResource(R.mipmap.index_bg_night_dark);
            sideslip_text.setTextColor(Color.WHITE);
            text.setTextColor(Color.WHITE);
        }
    }
    //EventBus卸载
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //EventBus卸载
        EventBus.getDefault().unregister(this);
    }
}